package net.lab1024.sa.base.module.support.elasticsearch.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.domain.EventBase;
import net.lab1024.sa.base.common.domain.EventBaseAlert;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.module.support.elasticsearch.domain.form.EventBaseEsQueryForm;
import net.lab1024.sa.base.module.support.elasticsearch.domain.form.SoarDisposalForm;
import net.lab1024.sa.base.module.support.elasticsearch.service.EventBaseEsService;
import net.lab1024.sa.base.utils.TextConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms;
import org.elasticsearch.search.aggregations.metrics.Max;
import org.elasticsearch.search.aggregations.metrics.ParsedMax;
import org.elasticsearch.search.aggregations.metrics.TopHits;


/**
 * 安全事件ES服务实现类
 *
 * @author chenyuqiang
 * @date 2025-01-27 10:00:00
 */
@Slf4j
@Service
public class EventBaseEsServiceImpl implements EventBaseEsService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public PageResult<EventBase> queryPage(EventBaseEsQueryForm queryForm) {
        try {
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 处理 KQL 转换后的 ES 查询条件
            if (queryForm.getEsQuery() != null) {
                QueryBuilder kqlQuery = parseEsQuery(queryForm.getEsQuery());
                if (kqlQuery != null) {
                    boolQuery.must(kqlQuery);
                }
            }

            // 处理时间范围查询
            if (StringUtils.isNotBlank(queryForm.getEventTimeBegin()) || StringUtils.isNotBlank(queryForm.getEventTimeEnd())) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // 解析为 LocalDateTime

                // 获取毫秒时间戳
                RangeQueryBuilder timeRangeQuery = QueryBuilders.rangeQuery("@timestamp");
                if (StringUtils.isNotBlank(queryForm.getEventTimeBegin())) {
                    Date parse = formatter1.parse(queryForm.getEventTimeBegin());
                    long time = parse.getTime();
                    long timestamp = LocalDateTime.parse(queryForm.getEventTimeBegin(), formatter).atZone(ZoneId.of("Asia/Shanghai")) // 设置时区（如 UTC+8）
                            .toInstant()
                            .toEpochMilli();
                    timeRangeQuery.gt(time);
                }
                if (StringUtils.isNotBlank(queryForm.getEventTimeEnd())) {
                    Date parse = formatter1.parse(queryForm.getEventTimeEnd());
                    long time = parse.getTime();
                    long timestamp = LocalDateTime.parse(queryForm.getEventTimeEnd(), formatter).atZone(ZoneId.of("Asia/Shanghai")).toInstant()
                            .toEpochMilli();
                    ;
                    timeRangeQuery.lte(time);
                }
                boolQuery.must(timeRangeQuery);
            }

            // 构建分页
            PageRequest pageRequest = PageRequest.of(queryForm.getPageNum() - 1, queryForm.getPageSize());

            // 构建排序
            String sortField = StringUtils.defaultIfBlank(queryForm.getSortField(), "@timestamp");
            Sort.Direction sortDirection = "asc".equalsIgnoreCase(queryForm.getSortOrder()) ? Sort.Direction.ASC : Sort.Direction.DESC;
            Sort sort = Sort.by(sortDirection, sortField);

            // 构建查询和聚合
            NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder()
                    .withQuery(boolQuery)
                    .withPageable(pageRequest)
                    .withSort(sort);
            // 添加聚合查询
            if (queryForm.getAggregationFields() != null && !queryForm.getAggregationFields().isEmpty()) {
                for (String field : queryForm.getAggregationFields()) {
                    // 创建terms聚合
                    TermsAggregationBuilder aggregation = AggregationBuilders
                            .terms(field + "_agg")
                            .field(field + ".keyword")  // 使用keyword类型进行精确聚合
                            .size(50);  // 限制聚合桶数量

                    // 添加top_hits子聚合，获取每个桶的样本数据
                    aggregation.subAggregation(
                            AggregationBuilders.topHits("top_hits")
                                    .size(1)  // 每个桶返回一条样本数据
                                    .sort("@timestamp", SortOrder.DESC)  // 按时间倒序
                    );

                    searchQueryBuilder.addAggregation(aggregation);
                }
            }

            // 执行查询
            SearchHits<EventBase> searchHits;
            if (StringUtils.isNotBlank(queryForm.getIndexName())) {
                searchHits = elasticsearchRestTemplate.search(
                        searchQueryBuilder.build(),
                        EventBase.class,
                        IndexCoordinates.of(queryForm.getIndexName())
                );
            } else {
                searchHits = elasticsearchRestTemplate.search(searchQueryBuilder.build(), EventBase.class);
            }

            // 构建返回结果
            List<EventBase> eventList = new ArrayList<>();

            // 处理聚合结果
            if (queryForm.getAggregationFields() != null && !queryForm.getAggregationFields().isEmpty() && searchHits.getAggregations() != null) {
                Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
                if (aggregations != null) {
                    // 用于存储所有聚合结果
                    List<EventBase> allAggregatedEvents = new ArrayList<>();

                    for (String field : queryForm.getAggregationFields()) {
                        String aggName = field + "_agg";
                        Terms terms = aggregations.get(aggName);
                        if (terms != null) {
                            for (Terms.Bucket bucket : terms.getBuckets()) {
                                // 获取top_hits结果
                                TopHits topHits = bucket.getAggregations().get("top_hits");
                                if (topHits.getHits().getHits().length > 0) {
                                    // 获取第一条样本数据
                                    org.elasticsearch.search.SearchHit hit = topHits.getHits().getHits()[0];
                                    // 将样本数据转换为EventBase对象
                                    EventBase aggregatedEvent = JSONObject.parseObject(hit.getSourceAsString(), EventBase.class);
                                    // 设置分组数量
                                    aggregatedEvent.setGroupCount(String.valueOf(bucket.getDocCount()));
                                    // 设置分组字段和值
                                    aggregatedEvent.setGroupKeys(field + ":" + bucket.getKeyAsString());
                                    allAggregatedEvents.add(aggregatedEvent);
                                }
                            }
                        }
                    }

                    // 对聚合结果进行分页处理
                    int fromIndex = (queryForm.getPageNum() - 1) * queryForm.getPageSize();
                    int toIndex = Math.min(fromIndex + queryForm.getPageSize(), allAggregatedEvents.size());

                    final List<EventBase> resultList = new ArrayList<>();
                    // 确保fromIndex不超过列表大小
                    if (fromIndex < allAggregatedEvents.size()) {
                        resultList.addAll(allAggregatedEvents.subList(fromIndex, toIndex));
                    }

                    PageResult<EventBase> pageResult = new PageResult<>();
                    pageResult.setList(resultList);
                    // 如果返回的数据总量大于10000，执行统计查询
                    pageResult.setTotal(searchHits.getTotalHits());
                    pageResult.setPageNum(Long.parseLong(queryForm.getPageNum() + ""));
                    pageResult.setPageSize(Long.parseLong(queryForm.getPageSize() + ""));

                    return pageResult;
                }
            } else {
                // 如果没有聚合，则返回原始搜索结果
                final List<EventBase> resultList = new ArrayList<>();
                searchHits.forEach(hit -> resultList.add(hit.getContent()));

                // 转换时间格式
                resultList.forEach(event ->
                        event.setEventTime(TextConversionUtils.convertToStandardFormat(event.getEventTime()))

                );

                PageResult<EventBase> pageResult = new PageResult<>();
                pageResult.setList(resultList);
                // 如果返回的数据总量大于10000，执行统计查询
                if (searchHits.getTotalHits() >= 10000) {
                    // 执行统计查询，保持与原始查询相同的条件
                    NativeSearchQuery countQuery = new NativeSearchQueryBuilder()
                            .withQuery(boolQuery)
                            .withMaxResults(0)  // 设置为0，因为我们只需要统计数量
                            .withTrackTotalHits(true)  // 设置track_total_hits为true，获取完整的统计数量
                            .build();

                    // 执行统计查询
                    SearchHits<EventBase> countHits;
                    if (StringUtils.isNotBlank(queryForm.getIndexName())) {
                        countHits = elasticsearchRestTemplate.search(countQuery, EventBase.class, IndexCoordinates.of(queryForm.getIndexName()));
                    } else {
                        countHits = elasticsearchRestTemplate.search(countQuery, EventBase.class);
                    }
                    pageResult.setTotal(countHits.getTotalHits());
                } else {
                    pageResult.setTotal(searchHits.getTotalHits());
                }
                pageResult.setPageNum(Long.parseLong(queryForm.getPageNum() + ""));
                pageResult.setPageSize(Long.parseLong(queryForm.getPageSize() + ""));

                return pageResult;
            }

        } catch (Exception e) {
            log.error("分页查询安全事件失败", e);
            throw new RuntimeException(e.getMessage());
        }
        return null;
    }
    public TermsAggregationBuilder groupBySrcIpDistinct() {
        // 1. 构建聚合查询
        TermsAggregationBuilder aggregation = AggregationBuilders.terms("group_by_src_ip")
                .field("src_ip.keyword")
                .size(100);  // 限制最大分组数

        // 2. 添加指标聚合获取最新事件时间
        aggregation.subAggregation(
                AggregationBuilders.max("latest_event_time").field("@timestamp")
        );
      return aggregation;
    }
    @Override
    public List<EventBase> queryList(EventBaseEsQueryForm queryForm) {
        try {
            // 构建查询条件
            BoolQueryBuilder boolQuery = buildBaseQuery(queryForm);

            log.info("查询参数：{}", queryForm.getEsQuery() != null ? queryForm.getEsQuery().toString() : "null");
            // 构建排序
            String sortField = StringUtils.defaultIfBlank(queryForm.getSortField(), "@timestamp");
            SortOrder sortOrder = "asc".equalsIgnoreCase(queryForm.getSortOrder()) ? SortOrder.ASC : SortOrder.DESC;

            // 构建查询
            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(boolQuery)
                    .withSort(SortBuilders.fieldSort(sortField).order(sortOrder))
                    .build();

            // 执行查询 - 支持指定索引名称
            SearchHits<EventBase> searchHits;
            if (StringUtils.isNotBlank(queryForm.getIndexName())) {
                // 使用指定的索引名称
                searchHits = elasticsearchRestTemplate.search(searchQuery, EventBase.class, IndexCoordinates.of(queryForm.getIndexName()));
            } else {
                // 使用默认索引
                searchHits = elasticsearchRestTemplate.search(searchQuery, EventBase.class);
            }

            // 构建返回结果
            List<EventBase> eventList = new ArrayList<>();
            searchHits.forEach(hit -> eventList.add(hit.getContent()));

            return eventList;
        } catch (Exception e) {
            log.error("查询安全事件列表失败", e);
            throw new RuntimeException("查询安全事件列表失败");
        }
    }
    @Override
    public List<EventBaseAlert> queryListAlert(EventBaseEsQueryForm queryForm) {
        try {
            // 构建查询条件
            BoolQueryBuilder boolQuery = buildBaseQuery(queryForm);

            log.info("查询参数：{}", queryForm.getEsQuery() != null ? queryForm.getEsQuery().toString() : "null");
            // 构建排序
            String sortField = StringUtils.defaultIfBlank(queryForm.getSortField(), "@timestamp");
            SortOrder sortOrder = "asc".equalsIgnoreCase(queryForm.getSortOrder()) ? SortOrder.ASC : SortOrder.DESC;

            // 构建查询
            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(boolQuery)
                    .withSort(SortBuilders.fieldSort(sortField).order(sortOrder))
                    .build();

            // 执行查询 - 支持指定索引名称
            SearchHits<EventBaseAlert> searchHits;
            if (StringUtils.isNotBlank(queryForm.getIndexName())) {
                // 使用指定的索引名称
                searchHits = elasticsearchRestTemplate.search(searchQuery, EventBaseAlert.class, IndexCoordinates.of(queryForm.getIndexName()));
            } else {
                // 使用默认索引
                searchHits = elasticsearchRestTemplate.search(searchQuery, EventBaseAlert.class);
            }

            // 构建返回结果
            List<EventBaseAlert> eventList = new ArrayList<>();
            searchHits.forEach(hit -> eventList.add(hit.getContent()));

            return eventList;
        } catch (Exception e) {
            log.error("查询安全事件列表失败", e);
            throw new RuntimeException("查询安全事件列表失败");
        }
    }
    @Override
    public Long getCount() {
        return getCount(null);
    }

    @Override
    public Long getCount(String indexName) {
        try {
            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.matchAllQuery())
                    .build();

            if (StringUtils.isNotBlank(indexName)) {
                return elasticsearchRestTemplate.count(searchQuery, EventBase.class, IndexCoordinates.of(indexName));
            } else {
                return elasticsearchRestTemplate.count(searchQuery, EventBase.class);
            }
        } catch (Exception e) {
            log.error("获取安全事件总数失败", e);
            throw e;
        }
    }

    @Override
    public EventBase getEventById(String eventId) {
        return getEventById(eventId, null);
    }

    @Override
    public EventBase getEventById(String eventId, String indexName) {
        EventBaseEsQueryForm queryForm = new EventBaseEsQueryForm();
        queryForm.setEventId(eventId);
        queryForm.setIndexName(indexName);
        PageResult<EventBase> eventBasePageResult = queryPage(queryForm);
        if(null!=eventBasePageResult){
            List<EventBase> list = eventBasePageResult.getList();
            if(null!=list && list.size()>0){
                return list.get(0);
            }
        }
       return null;
    }

    @Override
    public Map<String, Object> getEventTypeStats() {
        return getEventTypeStats(null);
    }

    @Override
    public Map<String, Object> getEventTypeStats(String indexName) {
        try {
            // 构建聚合查询
            TermsAggregationBuilder aggregation = AggregationBuilders
                    .terms("event_type_stats")
                    .field("event_type")
                    .size(50);

            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withAggregations(aggregation)
                    .withMaxResults(0)
                    .build();

            // 执行查询 - 支持指定索引名称
            SearchHits<EventBase> searchHits;
            if (StringUtils.isNotBlank(indexName)) {
                searchHits = elasticsearchRestTemplate.search(searchQuery, EventBase.class, IndexCoordinates.of(indexName));
            } else {
                searchHits = elasticsearchRestTemplate.search(searchQuery, EventBase.class);
            }

            // 处理结果
            Map<String, Object> stats = new HashMap<>();
            // TODO: 处理聚合结果
            return stats;
        } catch (Exception e) {
            log.error("获取事件类型统计失败", e);
            throw e;
        }
    }

    @Override
    public Map<String, Object> getSeverityStats() {
        try {
            // 构建聚合查询
            TermsAggregationBuilder aggregation = AggregationBuilders
                    .terms("severity_stats")
                    .field("severity")
                    .size(10);

            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withAggregations(aggregation)
                    .withMaxResults(0)
                    .build();

            // 执行查询
            SearchHits<EventBase> searchHits = elasticsearchRestTemplate.search(searchQuery, EventBase.class);

            // 处理结果
            Map<String, Object> stats = new HashMap<>();
            // TODO: 处理聚合结果
            return stats;
        } catch (Exception e) {
            log.error("获取危险等级统计失败", e);
            throw e;
        }
    }

    @Override
    public Map<String, Object> getGeoStats() {
        try {
            // 构建聚合查询
            TermsAggregationBuilder srcCountryAgg = AggregationBuilders
                    .terms("src_country_stats")
                    .field("geo_country")
                    .size(50);

            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withAggregations(srcCountryAgg)
                    .withMaxResults(0)
                    .build();

            // 执行查询
            SearchHits<EventBase> searchHits = elasticsearchRestTemplate.search(searchQuery, EventBase.class);

            // 处理结果
            Map<String, Object> stats = new HashMap<>();
            // TODO: 处理聚合结果
            return stats;
        } catch (Exception e) {
            log.error("获取地理位置统计失败", e);
            throw e;
        }
    }

    @Override
    public Map<String, Object> getTimeTrendStats(Map<String, Object> param) {
        try {
            // TODO: 实现时间趋势统计
            return new HashMap<>();
        } catch (Exception e) {
            log.error("获取时间趋势统计失败", e);
            throw e;
        }
    }

    @Override
    public String exportEvents(EventBaseEsQueryForm queryForm) {
        try {
            // TODO: 实现导出功能
            return "导出成功";
        } catch (Exception e) {
            log.error("导出安全事件数据失败", e);
            throw e;
        }
    }

    /**
     * 构建基础查询条件
     */
    private BoolQueryBuilder buildBaseQuery(EventBaseEsQueryForm queryForm) throws ParseException {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 处理 KQL 转换后的 ES 查询条件
        if (queryForm.getEsQuery() != null && !queryForm.getEsQuery().isEmpty()) {
            QueryBuilder kqlQuery = parseEsQuery(queryForm.getEsQuery());
            if (kqlQuery != null) {
                boolQuery.must(kqlQuery);
            }
        }

        // 时间范围
        if (queryForm.getStartTime() != null && queryForm.getEndTime() != null) {
            boolQuery.must(QueryBuilders.rangeQuery("@timestamp")
                    .from(queryForm.getStartTime())
                    .to(queryForm.getEndTime()));
        }
        if (StringUtils.isNotBlank(queryForm.getEventTimeBegin()) || StringUtils.isNotBlank(queryForm.getEventTimeEnd())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 解析为 LocalDateTime

            // 获取毫秒时间戳
            RangeQueryBuilder timeRangeQuery = QueryBuilders.rangeQuery("@timestamp");
            if (StringUtils.isNotBlank(queryForm.getEventTimeBegin())) {
                Date parse = formatter1.parse(queryForm.getEventTimeBegin());
                long time = parse.getTime();
                long timestamp = LocalDateTime.parse(queryForm.getEventTimeBegin(), formatter).atZone(ZoneId.of("Asia/Shanghai")) // 设置时区（如 UTC+8）
                        .toInstant()
                        .toEpochMilli();
                timeRangeQuery.gt(time);
            }
            if (StringUtils.isNotBlank(queryForm.getEventTimeEnd())) {
                Date parse = formatter1.parse(queryForm.getEventTimeEnd());
                long time = parse.getTime();
                long timestamp = LocalDateTime.parse(queryForm.getEventTimeEnd(), formatter).atZone(ZoneId.of("Asia/Shanghai")).toInstant()
                        .toEpochMilli();
                ;
                timeRangeQuery.lte(time);
            }
            boolQuery.must(timeRangeQuery);
        }

        // 处理关键词搜索
//        if (StringUtils.isNotBlank(queryForm.getKeyword())) {
//            boolQuery.must(QueryBuilders.multiMatchQuery(queryForm.getKeyword(),
//                    "event_name", "raw_log", "req_url", "req_body", "rsp_body"));
//        }
//
//        // 事件类型
//        if (queryForm.getEventTypes() != null && !queryForm.getEventTypes().isEmpty()) {
//            boolQuery.must(QueryBuilders.termsQuery("event_type", queryForm.getEventTypes()));
//        }
//
//        // 事件名称
//        if (StringUtils.isNotBlank(queryForm.getEventName())) {
//            boolQuery.must(QueryBuilders.termQuery("event_name", queryForm.getEventName()));
//        }
//
//        // 危险等级
//        if (queryForm.getSeverities() != null && !queryForm.getSeverities().isEmpty()) {
//            boolQuery.must(QueryBuilders.termsQuery("severity", queryForm.getSeverities()));
//        }
//
//        // 日志来源
//        if (queryForm.getLogSources() != null && !queryForm.getLogSources().isEmpty()) {
//            boolQuery.must(QueryBuilders.termsQuery("name", queryForm.getLogSources()));
//        }
//
//        // 源IP
//        if (StringUtils.isNotBlank(queryForm.getSrcIp())) {
//            boolQuery.must(QueryBuilders.termQuery("src_ip", queryForm.getSrcIp()));
//        }
//
//        // 目标IP
//        if (StringUtils.isNotBlank(queryForm.getDstIp())) {
//            boolQuery.must(QueryBuilders.termQuery("dst_ip", queryForm.getDstIp()));
//        }
//
//        // 设备名称
//        if (StringUtils.isNotBlank(queryForm.getDeviceName())) {
//            boolQuery.must(QueryBuilders.termQuery("device_name", queryForm.getDeviceName()));
//        }
//
//        // 设备IP
//        if (StringUtils.isNotBlank(queryForm.getDeviceIp())) {
//            boolQuery.must(QueryBuilders.termQuery("device_ip", queryForm.getDeviceIp()));
//        }
//
//        // 用户名
//        if (StringUtils.isNotBlank(queryForm.getUserName())) {
//            boolQuery.must(QueryBuilders.termQuery("user_name", queryForm.getUserName()));
//        }
//
//        // 处置结果
//        if (StringUtils.isNotBlank(queryForm.getBlocked())) {
//            boolQuery.must(QueryBuilders.termQuery("blocked", queryForm.getBlocked()));
//        }
//
        // SOAR处置结果
        if (StringUtils.isNotBlank(queryForm.getEventId())) {
            boolQuery.must(QueryBuilders.termQuery("event_id", queryForm.getEventId()));
        }

        return boolQuery;
    }

    /**
     * 解析前端传来的 ES 查询条件
     *
     * @param esQuery ES查询条件Map
     * @return QueryBuilder ES查询构建器
     */
    @SuppressWarnings("unchecked")
    private QueryBuilder parseEsQuery(Map<String, Object> esQuery) {
        if (esQuery == null || esQuery.isEmpty()) {
            return null;
        }

        // 处理 bool 查询
        if (esQuery.containsKey("bool")) {
            Map<String, Object> boolQuery = (Map<String, Object>) esQuery.get("bool");
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            // 处理 must 条件
            if (boolQuery.containsKey("must")) {
                List<Map<String, Object>> mustClauses = (List<Map<String, Object>>) boolQuery.get("must");
                for (Map<String, Object> clause : mustClauses) {
                    QueryBuilder queryBuilder = parseEsQuery(clause); // 递归处理嵌套的bool查询
                    if (queryBuilder != null) {
                        boolQueryBuilder.must(queryBuilder);
                    }
                }
            }

            // 处理 should 条件
            if (boolQuery.containsKey("should")) {
                List<Map<String, Object>> shouldClauses = (List<Map<String, Object>>) boolQuery.get("should");
                for (Map<String, Object> clause : shouldClauses) {
                    QueryBuilder queryBuilder = parseQueryClause(clause);
                    if (queryBuilder != null) {
                        boolQueryBuilder.should(queryBuilder);
                    }
                }
                // 设置最小匹配数
                if (boolQuery.containsKey("minimum_should_match")) {
                    int minimumShouldMatch = boolQuery.get("minimum_should_match") instanceof Integer ?
                            (Integer) boolQuery.get("minimum_should_match") :
                            Integer.parseInt(boolQuery.get("minimum_should_match").toString());
                    boolQueryBuilder.minimumShouldMatch(minimumShouldMatch);
                }
            }

            // 处理 must_not 条件
            if (boolQuery.containsKey("must_not")) {
                List<Map<String, Object>> mustNotClauses = (List<Map<String, Object>>) boolQuery.get("must_not");
                for (Map<String, Object> clause : mustNotClauses) {
                    QueryBuilder queryBuilder = parseQueryClause(clause);
                    if (queryBuilder != null) {
                        boolQueryBuilder.mustNot(queryBuilder);
                    }
                }
            }

            return boolQueryBuilder;
        }

        // 处理单个查询条件
        return parseQueryClause(esQuery);
    }

    /**
     * 解析查询子句
     *
     * @param clause 查询子句Map
     * @return QueryBuilder ES查询构建器
     */
    @SuppressWarnings("unchecked")
    private QueryBuilder parseQueryClause(Map<String, Object> clause) {
        if (clause == null || clause.isEmpty()) {
            return null;
        }

        // 处理 term 查询
        if (clause.containsKey("term")) {
            Map<String, Object> termQuery = (Map<String, Object>) clause.get("term");
            Map.Entry<String, Object> entry = termQuery.entrySet().iterator().next();
            return QueryBuilders.termQuery(entry.getKey(), entry.getValue());
        }

        // 处理 terms 查询
        if (clause.containsKey("terms")) {
            Map<String, Object> termsQuery = (Map<String, Object>) clause.get("terms");
            Map.Entry<String, Object> entry = termsQuery.entrySet().iterator().next();
            return QueryBuilders.termsQuery(entry.getKey(), (List<?>) entry.getValue());
        }

        // 处理 match 查询
        if (clause.containsKey("match")) {
            Map<String, Object> matchQuery = (Map<String, Object>) clause.get("match");
            Map.Entry<String, Object> entry = matchQuery.entrySet().iterator().next();
            if (entry.getValue() instanceof Map) {
                Map<String, Object> matchOptions = (Map<String, Object>) entry.getValue();
                return QueryBuilders.matchQuery(entry.getKey(), matchOptions.get("query"))
                        .operator(Operator.valueOf(((String) matchOptions.get("operator")).toUpperCase()));
            } else {
                return QueryBuilders.matchQuery(entry.getKey(), entry.getValue());
            }
        }

        // 处理 match_phrase 查询
        if (clause.containsKey("match_phrase")) {
            Map<String, Object> matchPhraseQuery = (Map<String, Object>) clause.get("match_phrase");
            Map.Entry<String, Object> entry = matchPhraseQuery.entrySet().iterator().next();
            return QueryBuilders.matchPhraseQuery(entry.getKey(), entry.getValue());
        }

        // 处理 range 查询
        if (clause.containsKey("range")) {
            Map<String, Object> rangeQuery = (Map<String, Object>) clause.get("range");
            Map.Entry<String, Object> entry = rangeQuery.entrySet().iterator().next();
            Map<String, Object> rangeParams = (Map<String, Object>) entry.getValue();
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(entry.getKey());

            if (rangeParams.containsKey("gt")) {
                rangeQueryBuilder.gt(rangeParams.get("gt"));
            }
            if (rangeParams.containsKey("gte")) {
                rangeQueryBuilder.gte(rangeParams.get("gte"));
            }
            if (rangeParams.containsKey("lt")) {
                rangeQueryBuilder.lt(rangeParams.get("lt"));
            }
            if (rangeParams.containsKey("lte")) {
                rangeQueryBuilder.lte(rangeParams.get("lte"));
            }

            return rangeQueryBuilder;
        }

        // 处理 wildcard 查询
        if (clause.containsKey("wildcard")) {
            Map<String, Object> wildcardQuery = (Map<String, Object>) clause.get("wildcard");
            Map.Entry<String, Object> entry = wildcardQuery.entrySet().iterator().next();
            return QueryBuilders.wildcardQuery(entry.getKey() + ".keyword", entry.getValue().toString());
        }

        // 处理 exists 查询
        if (clause.containsKey("exists")) {
            Map<String, Object> existsQuery = (Map<String, Object>) clause.get("exists");
            return QueryBuilders.existsQuery((String) existsQuery.get("field"));
        }

        return null;
    }



    @Override
    public String soarDisposal(SoarDisposalForm disposalForm) {
        try {
            log.info("开始SOAR处置，esId: {}, srcIp: {}", disposalForm.getEsId(), disposalForm.getSrcIp());

            // TODO: 这里实现具体的SOAR处置逻辑
            // 1. 根据esId查询事件详情
            // 2. 根据srcIp进行自动化处置
            // 3. 调用SOAR平台API
            // 4. 更新事件处置状态

            // 模拟处置过程
            Thread.sleep(1000);

            log.info("SOAR处置完成，esId: {}, srcIp: {}", disposalForm.getEsId(), disposalForm.getSrcIp());
            return "处置成功";
        } catch (Exception e) {
            log.error("SOAR处置失败，esId: {}, srcIp: {}", disposalForm.getEsId(), disposalForm.getSrcIp(), e);
            throw new RuntimeException("SOAR处置失败: " + e.getMessage());
        }
    }
} 